using namespace System.Data;
using namespace System.Data.SqlClient;

$excel = New-Object -ComObject Excel.Application;
$book = $excel.WorkBooks.Add();
$sheet = $book.WorkSheets.Item(1);
$connstr = "Database=Northgale;Integrated Security=SSPI";
$cn = New-Object SqlConnection $connstr;
$cn.Open();
$cmd = New-Object SqlCommand(
       "SELECT TOP 2000 * FROM dbo.Customers", $cn);
$cmd.CommandType = [CommandType]::Text;
$da = New-Object SqlDataAdapter($cmd);
$dt = New-Object DataTable;
$nrows = $da.Fill($dt);

$stopwatch = [System.Diagnostics.Stopwatch]::StartNew();
$ncols = $dt.Columns.Count;
$values = [System.Object[,]]::new($nrows, $ncols);
$rowno = 0;
foreach ($row in $dt.Rows) {
   $colno = 0;
   foreach ($item in $row.ItemArray) {
      $values[$rowno, $colno++] = $item.ToString();
   }
   $rowno++;
}
$sheet.Range($sheet.Cells(1, 1),
             $sheet.Cells($nrows, $ncols)) = $values;
$stopwatch.Stop();
[console]::WriteLine("Duration {0:F2} seconds.",
   $stopwatch.Elapsed.TotalSeconds);
$cmd.Dispose();
$cn.Close();
$cn.Dispose();
$excel.Visible = 1;
